<?php
namespace Modules\Frontend\Controllers;

class UserOrderController extends \Phalcon\Mvc\Controller {
	public function beforeExecuteRoute() {
		\Components\Utils::isClosedFrontent($this);
	}

	public function initialize() {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');
	}

	public function pagerAction() {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$query = $this -> request -> getQuery();
		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$service = $this -> account::getOrderLogicInstance() -> pager([
			'conditions' => 'user_id = ' . $serviceUser['user'] -> user_id
		], $query['limit'], $query['page']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $service['pager']]);
	}

	public function statusAction() {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$put = $this -> request -> getPut();
		if(!$this -> security -> checkHash($put['safePassword'], $serviceUser['user'] -> safe_password)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']);
		}

		$this -> db -> begin();
		try {
			switch($put['status']) {
				case 5:
				case '5':
					$serviceOrderProducts = $this -> account::getOrderProductsServiceInstance() -> find([
						'conditions' => 'user_order_id = ' . $put['user_order_id']
					]);
					if($serviceOrderProducts['code'] != 0) {
						return $this -> response -> setJsonContent(['code'=>$serviceOrderProducts['code'],'msg'=>$serviceOrderProducts['message']]);
					}
					$priceRMB = 0;
					$priceRetail = 0;
					$priceShop = 0;
					foreach($serviceOrderProducts['user_order_products'] as $product) {
						$priceRMB += $product -> price_rmb;
						$priceRetail += $product -> price_retail;
						$priceShop += $product -> price_shop;
					}

					if($priceRetail > 0) {
						$serviceRetail = $this -> account::getWalletServiceInstance() -> updateDecAmount(['type'=>1,'amount'=>$priceRetail,'user_id'=>$serviceUser['user'] -> user_id]);
						if($serviceRetail['code'] != 0) { throw new \Exception($serviceRetail['message']); }
					}

					if($priceShop > 0) {
						$serviceShop = $this -> account::getWalletServiceInstance() -> updateDecAmount(['type'=>3,'amount'=>$priceShop,'user_id'=>$serviceUser['user'] -> user_id]);
						if($serviceShop['code'] != 0) { throw new \Exception($serviceShop['message']); }
					}

					$voucherPicture = '';
					if(isset($put['imageContent']) && !empty($put['imageContent'])) {
						$saveFileName = date('Y').'/'.date('m').'/'.date('d');
						$path = PUBLIC_PACH . 'u/'.$saveFileName;
						$saveImage = \Components\Utils::base64_image_content($put['imageContent'], $path);
						if($saveImage['code'] != 0) {
							
						} else {
							$saveFileName .= '/'.$saveImage['file_name'];
							$voucherPicture = $saveFileName;
						}
					}
					$orderService = $this -> account::getOrderServiceInstance() -> update($put['user_order_id'], ['status' => $put['status'], 'voucher_picture' => $voucherPicture]);
					if($orderService['code'] != 0) { throw new \Exception('付款失败'); }
					break;
				case 21:
				case '21':
					$orderService = $this -> account::getOrderServiceInstance() -> update($put['user_order_id'], ['status' => $put['status']]);
					if($orderService['code'] != 0) { throw new \Exception($orderService['message']); }
					//if($orderService['code'] != 0) { throw new \Exception('收货失败'); }
					break;
				case 27:
				case '27':
					$orderService = $this -> account::getOrderServiceInstance() -> update($put['user_order_id'], ['status' => $put['status']]);
					//if($orderService['code'] != 0) { throw new \Exception($orderService['message']); }
					if($orderService['code'] != 0) { throw new \Exception('关闭失败'); }
					break;
				default:
					$orderService = $this -> account::getOrderServiceInstance() -> update($put['user_order_id'], ['status' => $put['status']]);
					if($orderService['code'] != 0) { throw new \Exception('未知操作'); }
			}

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		switch($put['status']) {
			case 5:
			case '5':
				return $this -> response -> setJsonContent(['code'=>0,'msg'=>'付款成功']);
			case 21:
			case '21':
				return $this -> response -> setJsonContent(['code'=>0,'msg'=>'收货成功']);
			case 27:
			case '27':
				return $this -> response -> setJsonContent(['code'=>0,'msg'=>'关闭成功']);
			default:
				return $this -> response -> setJsonContent(['code'=>0,'msg'=>'未知操作']);
		}
	}

	public function createAction() {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$post = $this -> request -> getPost();
		if(!$this -> security -> checkHash($post['safePassword'], $serviceUser['user'] -> safe_password)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']);
		}

		$productsIds = '';
		foreach($post['products'] as $id => $v) {
			$productsIds .= $id . ',';
		}
		$productsIds = rtrim($productsIds, ',');
		$serviceProducts = $this -> products::getServiceInstance() -> find([
			'conditions' => 'products_id in(' . $productsIds . ')'
		]);
		if($serviceProducts['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceProducts['code'],'msg'=>$serviceProducts['message']]);
		}

		$this -> db -> begin();
		try {
			$serviceUserOrder = $this -> account::getOrderServiceInstance() -> create([
				'user_id' => $serviceUser['user'] -> user_id,
				'user_address_id' => $post['addressId'],
				'status' => 3,
				'create_time' => time()
			]);
			if($serviceUserOrder['code'] != 0) { throw new \Exception($serviceUserOrder['message']); }

			$userOrderProductsData = [
				'user_order_id' => $serviceUserOrder['user_order'] -> user_order_id
			];

			$priceRMB = 0;
			$priceRetail = 0;
			$priceShop = 0;
			foreach($serviceProducts['productses'] as $product) {
				$userOrderProductsData['amount'] = $post['products'][$product -> products_id]['amount'];
				$userOrderProductsData['products_id'] = $product -> products_id;
				$userOrderProductsData['name'] = $product -> name;
				$userOrderProductsData['images'] = $product -> images;
				$userOrderProductsData['price_rmb'] = $product -> price_rmb;
				$priceRMB += $userOrderProductsData['amount'] * $product -> price_rmb;
				$userOrderProductsData['price_retail'] = $product -> price_retail;
				$priceRetail += $userOrderProductsData['amount'] * $product -> price_retail;
				$userOrderProductsData['price_shop'] = $product -> price_shop;
				$priceShop += $userOrderProductsData['amount'] * $product -> price_shop;
				$serviceUserOrderProducts = $this -> account::getOrderProductsServiceInstance() -> create($userOrderProductsData);
				if($serviceUserOrderProducts['code'] != 0) { throw new \Exception($serviceUserOrderProducts['message']); }
			}

			if($priceRMB <= 0) {
				if($priceRetail > 0) {
					$serviceRetail = $this -> account::getWalletServiceInstance() -> updateDecAmount(['type'=>1,'amount'=>$priceRetail,'user_id'=>$serviceUser['user'] -> user_id]);
					if($serviceRetail['code'] != 0) { throw new \Exception($serviceRetail['message']); }
				}

				if($priceShop > 0) {
					$serviceShop = $this -> account::getWalletServiceInstance() -> updateDecAmount(['type'=>3,'amount'=>$priceShop,'user_id'=>$serviceUser['user'] -> user_id]);
					if($serviceShop['code'] != 0) { throw new \Exception($serviceShop['message']); }
				}

				$serviceUserOrder['user_order'] -> status = 5;
				if(!$serviceUserOrder['user_order'] -> save()) { throw new \Exception('下单失败'); }
			}

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'下单成功']);
	}
}